<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:v-on="http://www.w3.org/1999/xhtml">

<head th:replace="main :: common_head"></head>
<style>
    [v-cloak] {
        display: none;
    }

    /*.caret {*/
    /*    display: inline-block;*/
    /*    width: 0;*/
    /*    height: 0;*/
    /*    margin-left: 2px;*/
    /*    vertical-align: middle;*/
    /*    border-top: 4px dashed;*/
    /*    border-top: 4px solid \9;*/
    /*    border-right: 4px solid transparent;*/
    /*    border-left: 4px solid transparent;*/
    /*}*/
</style>

<body>
<input type="hidden" id="graphId" th:value="${graphId}">

<div id="app">
    <div class="container-fluid-full">
        <div class="row-fluid">
            <!-- start: Content -->
            <div id="content" class="span10" style="width: 100%;">
                <!--<input type="hidden" id="graphId" th:value="${graphId}">-->
                <ul class="breadcrumb" th:if="${#request.getParameter('breadcrumb') == 'true'}">
                    <li>
                        <i class="fas fa-circle-notch"></i>
                        <a id="home" href="#" onclick="parent.location.reload()">主页</a>
                        <i class="icon-angle-right"></i>
                    </li>
                    <li><a href="#">知识图谱</a></li>
                </ul>

                <!-- 选择开始 -->
                <div class="container" style="margin-left:0px">
                    <ul id="mytab" class="nav nav-pills nav-justified">
                        <li role="presentation" class="dropdown" id="myli">
                            <div style="border:1px solid black; border-radius: 5px; padding:0px 12px; line-height: 32px;">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" style="display: inline-block; text-decoration:none;" th:text="${currentGraph.graphName}"></a>
                                <span class="caret" style="display: inline-block; margin-top: 16px"></span>
                            </div>
                            <ul class="dropdown-menu">
                                <li th:each="graph,graphStat:${graphList}" role="presentation" th:id="'li'+${graph.graphId}">
                                    <a th:href="@{/relationship/viewDragPage/{graphId}(graphId=${graph.graphId})}" th:text="${graph.graphName}"></a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <!-- 选择结束 -->

                <div style="position: absolute;top: 80px;right: 50px;z-index: 999">
                    <button class="button-login" type="button" id="saveV">保存</button>
                </div>

                <div class="row-fluid sortable">
                    <div style="width:93%;height:900px;background-color: #578ebe;padding: 50px;">
                        <div id="graphContainer" style="position:relative;width:100%;height:800px;cursor:default;"></div>
                    </div><!--/span-->
                    <!--<button class="button-login" type="button" onclick="drawChart1()">生成策略</button>-->
                </div><!--/row-->
            </div><!--/.fluid-container-->
        </div>
        <!-- end: Content -->
    </div><!--/#content.span10-->
    </div><!--/fluid-row-->
</div>

<div th:replace="main::common_js"></div>

<!-- 引入mxClient.js会报错，原因是路径问题 -->
<!--<script th:src="@{/js/mxClient.js}"></script>-->

<script>
    breadcrumb()
    parent.modifyTitle('图谱位置调整')
</script>

<script th:src="@{/js/detect-element-resize.js}"></script>
<script th:src="@{/js/iframe-resize.js}"></script>

<script>
    mxBasePath = '../static';
</script>
<!-- Example code -->
<script type="text/javascript">
    // var graph = new mxGraph(document.getElementById("graphContainer"));
    $(function () {
        var location = window.location.href;//获取网页地址
        console.log(location);
        var id = location.substring(location.lastIndexOf('/') + 1);//获取/后的id
        if (id.lastIndexOf('?') != -1) {
            id = id.substring(0, id.lastIndexOf('?'))
        }
        console.log("当前id" + id);
        $("#" + "li" + id).addClass("active");//对应li高亮
    })
    // $(document).ready(function () { })
    var graph = document.getElementById("graphId");
    console.log(graph.value);
    window.onload = function () {
        var location = window.location.href;
        var id = location.substring(location.lastIndexOf('/') + 1);
        if (id.lastIndexOf('?') != -1) {
            id = id.substring(0, id.lastIndexOf('?'))
        }
        console.log(id);
        $("#" + "li" + id).addClass("active").siblings().removeClass("active");
        console.log("开始1");
        main(document.getElementById("graphContainer"), graph.value);
    };

    // 获取当前页面的滚动位置
    function getScrollPosition() {
        return {
            x: window.pageXOffset !== undefined ? window.pageXOffset : window.scrollX,
            y: window.pageYOffset !== undefined ? window.pageYOffset : window.scrollY
        }
    }

    function main(container, graphId) {
        // 判断浏览器是否支持
        if (!mxClient.isBrowserSupported()) {
            // mxUtils报错提示
            mxUtils.error('Browser is not supported!', 200, false);
        } else {
            var graph = new mxGraph(container);

            //去锯齿效果
            mxRectangleShape.prototype.crisp = true;
            // 显示导航线
            mxGraphHandler.prototype.guidesEnabled = true;
            // Alt键禁用导航线
            mxGuide.prototype.isEnabledForEvent = function (evt) {
                return !mxEvent.isAltDown(evt);
            };
            // 显示终点
            mxEdgeHandler.prototype.snapToTerminals = false;
            // 禁用浏览器默认的右键菜单栏
            mxEvent.disableContextMenu(container);

            // 在已有容器内构造一个graph
            // 鼠标框选
            new mxRubberband(graph);
            // 在图形中创建默认组件
            var parent = graph.getDefaultParent();
            // 只可预览不可选中拖动连接
            graph.setEnabled(true);
            // 容器大小自适应
            graph.setResizeContainer(true);
            // 动态改变样式
            graph.getView().updateStyle = true;
            // 可否重复连接
            graph.setMultigraph(false);
            // 禁止改变元素大小
            graph.setCellsResizable(false);
            // 允许连线的目标和源是同一元素
            graph.setAllowLoops(true);
            // graph.setCellsLocked(false);
            // 开始往module里添加cell
            graph.getModel().beginUpdate();
            try {
                //new一个cell 以单元的形式创建一个节点
                // var cell = new mxCell(null, new mxGeometry(100, 200, 100, 100), "一些样式配置");//节点创建
                // cell.vertex = true;
                // //插入这个cell
                // graph.addCell(cell); //添加节点

                // var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
                // var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
                // console.log(typeof v1);
                //插入线条设置连接图形
                $.ajax({
                    type: "GET",
                    url: "/multipower/relationship/getGraphDragChart/" + graphId,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        console.log("data" + data);
                        console.log(data)
                        console.log(typeof data);
                        console.log(typeof data.node);

                        console.log(window.innerWidth / 2 + 'px')
                        console.log(window.screen.width / 2 + 'px')
                        console.log(window.screen.height / 2 + 'px')


                        if (data.node.length == 0) {
                            // 这里调用父页面的方法是因为这个页面是嵌入到iframe中的，要想居中，只能在父页面中弹出提示框
                            if (window.parent.layerAlert != undefined) {
                                window.parent.layerAlert("当前图谱无设备，请添加！", {
                                    icon: 5,
                                    title: "提示"
                                })
                            } else {
                                layer.alert('当前图谱无设备，请添加！', {
                                    icon: 5,
                                    title: "提示",
                                    offset: '30%'
                                });
                            }
                            return false;
                        } else {
                            var node = data.node;//设备
                            var edge = data.edge;//边
                            var nodeLength = data.node.length;//设备长度
                            var edgeLength = data.edge.length;//边长度
                            console.log(edge);
                            console.log(node);
                            console.log("长度为:" + nodeLength);
                            var vertext = [];//存放节点名称变量的数组
                            var style = {};
                            var styleName = [];//存放样式名称的数组
                            for (var j = 0; j < nodeLength; j++) {
                                vertext[j] = {};
                                var style = graph.getStylesheet().getDefaultVertexStyle();//获取默认样式
                                var style1 = mxUtils.clone(style);//拷贝默认样式
                                style1[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_LABEL;
                                style1[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER;
                                style1[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_BOTTOM;
                                style1[mxConstants.STYLE_IMAGE_ALIGN] = mxConstants.ALIGN_CENTER;
                                style1[mxConstants.STYLE_IMAGE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP;
                                style1[mxConstants.STYLE_STROKECOLOR] = "transparent"; //背景边框
                                style1[mxConstants.STYLE_FILLCOLOR] = "transparent";//填充颜色
                                style1[mxConstants.STYLE_FONTCOLOR] = "white";//字体颜色
                                style1[mxConstants.STYLE_FONTSIZE] = "14";//字体大小
                                style1[mxConstants.LABEL_HANDLE_SIZE] = 10; //标签大小
                                style1[mxConstants.STYLE_IMAGE_WIDTH] = 50;//图片宽高
                                style1[mxConstants.STYLE_IMAGE_HEIGHT] = 50;
                                style1[mxConstants.STYLE_IMAGE] = node[j].picPath;//图片路径
                                styleName[j] = 'style' + j;
                                graph.getStylesheet().putCellStyle(styleName[j], style1);//将样式放入全局
                                vertext[j] = graph.insertVertex(parent, node[j].deviceId,
                                    node[j].deviceName+"["+node[j].deviceId+"]", node[j].coordinate[0], node[j].coordinate[1], 80, 80, styleName[j]);
                                 console.log(vertext[j]);
                            }
                            //  for(var i=0;i<edgeLength;i++){
                            //     graph.insertEdge(parent,null,'',graph.insertVertex(parent, edge[i].desc.split("#")[0], edge[i].deviceName[0], edge[i].line[0][0], edge[i].line[0][1], 80, 30),
                            //         graph.insertVertex(parent, edge[i].desc.split("#")[1], edge[i].deviceName[1], edge[i].line[1][0], edge[i].line[1][1], 80, 30))
                            // }

                            var styleEdge = graph.getStylesheet().getDefaultEdgeStyle();
                            var styleEdge1 = mxUtils.clone(styleEdge);
                            styleEdge1[mxConstants.STYLE_FONTCOLOR] = "white";
                            styleEdge1[mxConstants.STYLE_FONTSIZE] = "14";
                            styleEdge1[mxConstants.STYLE_STROKECOLOR] = "white";

                            graph.getStylesheet().putCellStyle('styleEdge1', styleEdge1);
                            for (var indexV = 0; indexV < nodeLength; indexV++) {
                                for (var i = 0; i < nodeLength; i++) {
                                    var desc = node[indexV].deviceId.toString() + "#" + node[i].deviceId.toString();
                                    for (var j = 0; j < edgeLength; j++) {
                                        if (desc == edge[j].desc) { //边匹配
                                            // graph.insertEdge(parent, null, '传递', vertext[indexV], vertext[i], 'styleEdge1');
                                            graph.insertEdge(parent, null, null, vertext[indexV], vertext[i], 'styleEdge1');
                                        }
                                    }
                                }
                            }
                        }
                    }
                })
                // var e1 = graph.insertEdge(parent, null, '', graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30), graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30));

                //预览时鼠标悬浮到节点时，改变鼠标样式
                graph.getCursorForCell = function (cell) {
                    if (cell != null && cell.value != null && cell.vertex == 1) {
                        return 'pointer';
                    }
                };
                $("#saveV").click(function () {
                    var encoder = new mxCodec(); //
                    var node = encoder.encode(graph.getModel());
                    console.log(node);
                    var xml = mxUtils.getXml(node);
                    console.log(xml);
                    console.log(typeof xml);
                    $.ajax({
                        type: "POST",
                        url: "/multipower/device/updateDeviceCoordinates?graphId=" + graphId,
                        dataType: "json",
                        async: false,
                        data: {xmlString: xml},
                        success: function (data) {
                            if (data.message == 'success') {
                                if (window.parent.layerAlert != undefined) {
                                    window.parent.layerAlert("保存成功!", {
                                        icon: 6,
                                        title: "提示"
                                    })
                                } else {
                                    layer.alert('保存成功!', {
                                        icon: 6,
                                        title: "提示",
                                        offset: '30%'
                                    });
                                }
                            }
                        }
                    })
                })
            } finally {
                // 更新事务结束
                graph.getModel().endUpdate();
            }
        }
    };

    // function create_variable(num){
    //
    //   var name = "test_"+num;   //生成函数名
    //   window[name]={};
    //   window['name'];   //注意看中括号里的内容加引号和不加引号的区别
    // }
    //  create_variable(13);
    //  console.log(test_13);
</script>
</body>
</html>